package com.lx.ui;

import com.lx.controller.AdminController;
import com.lx.controller.BankCardController;
import com.lx.controller.TradeController;
import com.lx.controller.UserController;
import com.lx.entity.BankCard;
import com.lx.entity.Trade;
import com.lx.entity.User;
import com.lx.entity.vo.BankCardAndUserInfo;
import com.lx.entity.vo.TradeAndCardInfoVO;
import com.lx.entity.vo.UserVo;
import com.lx.uitl.MD5Util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

/**
 * @author c先生
 * @date 2022年05月05日 下午 3:57:07
 * @describe
 */

public class Main {
    static User loginUser = null;
    static Scanner sc = new Scanner(System.in);
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    static UserController userController = new UserController();
    static AdminController adminController = new AdminController();
    static BankCardController bankCardController = new BankCardController();
    static TradeController tradeController = new TradeController();

    public static void main(String[] args) {


        boolean flag = true;
        while (true) {
            System.out.println("1.注册");
            System.out.println("2.登录");
            System.out.println("请选择：");
            int index = sc.nextInt();
            switch (index) {
                case 1:
                    //注册用户
                    System.out.println("请输入用户名：");
                    String name = sc.next();
                    System.out.println("请输入用户密码：");
                    String password = sc.next();
//                    System.out.println("请输入用户状态：（用户状态 0正常使用 1冻结  2注销）");
                    Integer status = 0;//新用户注册默认为0
                    System.out.println("请输入用户手机号：");
                    String phoneNumber = sc.next();
                    System.out.println("请输入用户地址：");
                    String address = sc.next();
                    //System.out.println("请输入用户等级：");
                    Integer level = 0;//默认为0级
                    System.out.println("请输入用户生日：");
                    String date = sc.next();
                    Date birthday = null;
                    try {
                        birthday = sdf.parse(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    System.out.println("请输入用户性别：");
                    String geder = sc.next();
//                    System.out.println("请输入用户开户时间：");
                    Date openAccountTime = new Date();//默认为现在
                    System.out.println("请输入用户身份证号：");
                    String card = sc.next();
                    User user = new User(name, password, status, phoneNumber, address, level, birthday, geder, openAccountTime, card);
                    Integer flag1 = userController.registerUser(user);
                    if (flag1 != null || flag1 != 0) {
                        System.out.println("注册成功！");
                    } else {
                        System.out.println("注册失败！");
                    }
                    break;
                case 2:
                    Boolean flag2 = false;
                    System.out.println("请输入用户名：");
                    String name2 = sc.next();
                    System.out.println("请输入密码：");
                    String password2 = sc.next();
                    password2 = MD5Util.md5(password2);
                    //登录成功进入系统
                    if (name2.contains("admin")) {
                        //管理员登录
                        String pwd = adminController.loginAdmin(name2);
                        if (password2.equals(pwd)) {
                            flag2 = true;
                        }
                        if (flag2) {//管理员登录成功，进入管理员界面
                            System.out.println("管理员登录成功！");
                            boolean flag3 = true;
                            a:
                            while (true) {
                                System.out.println("1.添户添卡");
                                System.out.println("2.查看所有用户信息");
                                System.out.println("3.客户销户");
                                System.out.println("4.银行卡冻结");
                                System.out.println("5.银行卡销卡");
                                System.out.println("6.退出管理员用户");

                                System.out.println("请选择：");
                                int index1 = sc.nextInt();
                                switch (index1) {
                                    case 1:
                                        //注册用户
                                        System.out.println("请输入用户手机号：");
                                        String phoneNumber1 = sc.next();
                                        Integer userIds = userController.getUserIdByPhone(phoneNumber1);
                                        if (userIds != null && userIds != 0) {
                                            System.out.println("此用户已存在直接开卡");
                                            System.out.println("请输入卡号");
                                            String cardId = sc.next();
                                            System.out.println("请输入卡的密码");
                                            String cardPassword = sc.next();
                                            System.out.println("卡的余额");
                                            Double balance = sc.nextDouble();
                                            //System.out.println("卡的状态");
                                            Integer cardStatus = 0;
                                            //System.out.println("请输入开卡日期");
                                            Date openCard = new Date();
                                            BankCard bankCard = new BankCard(cardId, userIds, cardPassword, balance, cardStatus, openCard);
                                            boolean addCardFlag = bankCardController.addBankCard(bankCard);
                                            if (addCardFlag) {
                                                System.out.println("添加成功");
                                            } else {
                                                System.out.println("添加失败");
                                            }
                                        } else {
                                            System.out.println("不存在去注册");
                                        }
                                        break;

                                    case 2:
                                        List<UserVo> list = userController.getAll();
                                        for (UserVo userVo : list) {
                                            System.out.println(userVo);
                                        }
                                        break;

                                    case 3:
                                        break;
                                    case 4:
                                        System.out.println("请输入要冻结的用户银行卡：");
                                        String freezeCardId = sc.next();
                                        boolean freezeFlag = bankCardController.freeze(freezeCardId);
                                        if (freezeFlag) {
                                            System.out.println("冻结成功");
                                        } else {
                                            System.out.println("冻结失败");
                                        }
                                        break;
                                    case 5:
                                        System.out.println("请输入要注销的卡号");
                                        String updateCardId = sc.next();
                                        boolean updateStatus = bankCardController.updateStatusByCardId(updateCardId);
                                        if (updateStatus) {
                                            System.out.println("注销成功");
                                        } else {
                                            System.out.println("注销失败");
                                        }

                                        break;
                                    case 6:
                                        System.out.println("是否退出登录");
                                        break a;
                                    default:
                                        System.out.println("输入错误");
                                        break;
                                }
                                System.out.println("请选择：y/n");
                                String key1 = sc.next();
                                if (key1.equals("y")) {
                                    flag3 = true;
                                } else if (key1.equals("n")) {
                                    flag3 = false;
                                } else {
                                    System.out.println("输入错误");
                                    System.exit(0);
                                }
                            }
                        } else {//管理员登录失败
                            System.out.println("管理员登录失败！");
                        }
                    } else {//用户登录
                        String pwd = userController.loginUser(name2);
                        if (password2.equals(pwd)) {
                            flag2 = true;
                        }
                        if (flag2) {
                            //用户登录成功，进入用户界面
                            loginUser = userController.getUserInfoByName(name2);
                            System.out.println("用户登录成功！");
                            boolean userFlag = true;
                            a:
                            while (userFlag) {
                                System.out.println("1.查询余额");
                                System.out.println("2.存款");
                                System.out.println("3.取款");
                                System.out.println("4.转账");
                                System.out.println("5、办理新的银行卡");
                                System.out.println("6、查询账户近30天的交易流水");
                                System.out.println("7、查询某张卡上个月的交易流水");
                                System.out.println("8、退出系统");
                                System.out.println("请输入您的选择：");
                                int choice = sc.nextInt();
                                switch (choice) {
                                    case 1:
                                        selectBalance();
                                        break;
                                    case 2:
                                        System.out.println("请输入手机号：");
                                        String phone = sc.next();
                                        List<BankCard> list = tradeController.findBankCardByPhone(phone);
                                        if (list != null) {
                                            System.out.println("您名下的银行卡信息：");
                                            for (BankCard bankCard : list) {
                                                System.out.println(bankCard);
                                            }
                                        } else {
                                            System.out.println("您没有银行卡，请先开卡！");
                                        }
                                        System.out.println("请输入银行卡卡号：");
                                        String cardId = sc.next();
                                        System.out.println("请输入存款金额：");
                                        double money = sc.nextDouble();
                                        boolean saveFlag = tradeController.saveMoney(money, cardId);
                                        if (saveFlag) {
                                            System.out.println("存款成功！");
                                        } else {
                                            System.out.println("存款失败！");
                                        }
                                        break;
                                    case 3:
                                        withdrawal();
                                        /*System.out.println("请输入手机号：");
                                        String phone1 = sc.next();
                                        List<BankCard> list1 = tradeController.findBankCardByPhone(phone1);
                                        if (list1 != null) {
                                            System.out.println("您名下的银行卡信息：");
                                            for (BankCard bankCard : list1) {
                                                System.out.println(bankCard);
                                            }
                                        } else {
                                            System.out.println("您没有银行卡，请先开卡！");
                                        }
                                        System.out.println("请输入银行卡卡号：");
                                        String takeCardId = sc.next();
                                        System.out.println("请输入取款金额：");
                                        double takeMoney = sc.nextDouble();
                                        boolean takeFlag = tradeController.takeMoney(takeMoney, takeCardId);
                                        if (takeFlag) {
                                            System.out.println("取款成功！");
                                        } else {
                                            System.out.println("取款失败！");
                                        }
                                        break;*/
                                        break;
                                    case 4:
                                        //转账 @author 牛园
                                        charge();
                                        break;
                                    case 5:
                                        //办理新的银行卡
                                        openCard();
                                        break;
                                    case 6:
                                        //查询账户上个月的交易流水
                                        selectLastMonthRecord();
                                        break;
                                    case 7:
                                        //查询某张卡上个月的交易流水
                                        selectLastMonthRecordByCard();
                                        break;
                                    case 8:
                                        System.exit(0);
                                        break;
                                    default:
                                        System.out.println("输入有误，请重新输入");
                                        break;
                                }
                                System.out.println("请选择：y/n");
                                String c = sc.next();
                                if (c.equals("y")) {
                                    userFlag = true;
                                } else if (c.equals("n")) {
                                    userFlag = false;
                                } else {
                                    System.out.println("输入错误");
                                    System.exit(0);
                                }
                            }
                        } else {//用户登录失败
                            System.out.println("用户登录失败！");
                        }
                        //普通用户登录
                    }
                    break;
                default:
                    System.out.println("输入错误");
                    break;
            }
            System.out.println("请选择：y/n");
            String key = sc.next();
            if (key.equals("y")) {
                flag = true;
            } else if (key.equals("n")) {
                flag = false;
            } else {
                System.out.println("输入错误：");
                System.exit(0);
            }

        }
    }

    /**
     * 转账
     */
    private static void charge() {
        //暂时模拟已经登录的模拟用户的个人信息
        //pwd=123456
        /*  User user = new User(900001, "张恒", "e10adc3949ba59abbe56e057f20f883e", 0, "123478596", "湖南", 1, new Date(), "男", new Date(), "420365816584646");*/
        //转账需要先进行登录  登录后根据保存的信息获取自己名下的银行卡信息（包含银行卡卡号，以及余额，让用户去选择，使用哪一张银行卡去支付）
        //获取到的银行卡列表
        List<BankCard> list = bankCardController.findCardsByUserId(loginUser.getUserId());
        if (list.size() <= 0) {
            //小于0 名下没有银行卡 ，应该先进行开卡，然后再进行转账存取款业务
            System.out.println("您名下没有银行卡，请先进行开卡，再进行转账存取款业务");
            return;
        }
        while (true) {
            System.out.println("请选择您名下的的付款银行卡");
            //if判断过则说明名下有银行卡，进行循环展示
            for (int i = 0; i < list.size(); i++) {
                BankCard card = list.get(i);
                System.out.println((i + 1) + "、卡号：" + card.getCardId() + " 余额：" + card.getCardBalance());
            }
            int num = sc.nextInt();
            if (num > list.size()) {
                System.out.println("输入错误请重新输入");
            } else {
                //获取到的付款银行卡
                BankCard cardForPay = list.get(num - 1);
                //转账
                while (true) {
                    System.out.println("请输入转账的银行卡号");
                    //输入的银行卡号
                    String cardId = sc.next();
                    //获取到的银行卡数量
                    int cardCount = bankCardController.findCardCountById(cardId);
                    if (cardCount == 1) {
                        //查询到该银行卡有且只有一张
                        BankCardAndUserInfo bankCardAndUserInfo = bankCardController.findCardInfoById(cardId);
                        //获取名字的长度，将名字只保留第一个，余下的都转换成*号
                        int nameLength = bankCardAndUserInfo.getUserName().length();
                        //姓
                        String firstName = bankCardAndUserInfo.getUserName().substring(0, 1);
                        StringBuilder sb = new StringBuilder(firstName);
                        for (int i = 0; i < nameLength - 1; i++) {
                            sb.append("*");
                        }
                        while (true) {
                            System.out.println("请输入转账收款人的姓名全称（" + sb + "）");
                            String inputName = sc.next();
                            if (!inputName.equals(bankCardAndUserInfo.getUserName())) {
                                System.out.println("您输入的转账人名称不正确，为确保您的资金安全，请核对");

                            } else {
                                BankCard bankCard = bankCardAndUserInfo.getBankCard();
                                //获取到的银行卡余额
                                double balance = bankCard.getCardBalance();
                                while (true) {
                                    System.out.println("请输入转账的金额-----当前卡上余额：" + balance);
                                    //要转出的金额
                                    double payMoney = sc.nextDouble();
                                    if (payMoney > balance) {
                                        //如果转出的金额大于卡上余额
                                        System.out.println("卡上余额不足，请重新输入金额");
                                    } else {
                                        System.out.println("请输入转账备注");
                                        String remark = sc.next();
                                        if (remark == null) {
                                            remark = "无";
                                        }
                                        //开始执行转账操作
                                        Trade trade = new Trade();
                                        //设置交易类型为转账
                                        trade.setBusinessType(3);
                                        trade.setCardId(cardForPay.getCardId());
                                        trade.setPayeeCard(cardId);
                                        trade.setTransTime(new Date());
                                        trade.setTransMoney(payMoney);
                                        trade.setRemark(remark);
                                        boolean flag = bankCardController.transfer(trade);
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        //该break是为了跳出最外面一层while
                        break;
                    } else if (cardCount == 0) {
                        System.out.println("无此银行卡信息，请核对后重新您输入");
                    } else {
                        System.out.println("未知错误");
                        break;
                    }
                }
                //该break是为了结束转账流程
                System.out.println("转账完成");
                break;
            }
        }

    }

    /**
     * 查询账户余额
     *
     * @author: 元初
     */
    private static void selectBalance() {
        //拿到该用户名下所有的银行卡信息
        List<BankCard> list = bankCardController.findCardsByUserId(loginUser.getUserId());
        //遍历输出
        double sumBalance = 0;
        for (BankCard bankCard : list) {
            System.out.println("卡号:" + bankCard.getCardId() + " 余额:" + bankCard.getCardBalance());
            sumBalance += bankCard.getCardBalance();
        }
        System.out.println("账户总余额:" + sumBalance);
    }

    /**
     * 随机生成19位的银行卡号
     *
     * @return 生成19位的银行卡号字符串
     */
    private static String getRandomCardNo() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 19; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 开卡
     *
     * @author: 元初
     */
    private static void openCard() {
        BankCard bankCard = new BankCard();
        String cardId = getRandomCardNo();
        bankCard.setCardId(cardId);
        //card_id、users_id、card_pwd、card_balance、card_status、open_card
        bankCard.setUsersId(loginUser.getUserId());
        while (true) {
            System.out.println("请输入银行卡密码（输入1默认为6个6）");
            String pwd = sc.next();
            if (pwd.equals("1")) {
                bankCard.setCardPwd("666666");
            } else {
                bankCard.setCardPwd(pwd);
            }
            break;
        }
        bankCard.setCardBalance(0.0);
        bankCard.setCardStatus(0);
        bankCard.setOpenCard(new Date());
        boolean isSuccess = bankCardController.addBankCard(bankCard);
        if (isSuccess) {
            System.out.println("开卡成功");
        } else {
            System.out.println("未知错误，开卡失败");
        }
    }

    /**
     * 查询某一张卡最近30天的交易记录
     */
    private static void selectLastMonthRecordByCard() {
        while (true) {
            System.out.println("请选择要查询交易流水的银行卡");
            List<BankCard> cardList = bankCardController.findCardsByUserId(loginUser.getUserId());
            if (cardList.size() <= 0) {
                System.out.println("暂未开卡，请进行开卡");
                return;
            }
            for (int i = 0; i < cardList.size(); i++) {
                System.out.println((i + 1) + ":" + cardList.get(i));
            }
            int choice = sc.nextInt();
            if (choice > cardList.size()) {
                System.out.println("选择有误，请重新选择");
            } else {
                List<TradeAndCardInfoVO> list = bankCardController.selectLastMonthRecordByCard(cardList.get(choice - 1).getCardId());
                for (TradeAndCardInfoVO tradeInfo : list) {
                    System.out.println(tradeInfo);
                }
                break;
            }
        }

       /* String cardNo = sc.next();
        List<TradeAndCardInfoVO> list = bankCardController.selectLastMonthRecordByCard(cardNo);
        for (TradeAndCardInfoVO tradeInfo : list) {
            System.out.println(tradeInfo);
        }*/
    }

    /**
     * 查询最近30天的交易记录
     */
    private static void selectLastMonthRecord() {
        List<TradeAndCardInfoVO> list = bankCardController.getAccountLastMonthRecord(loginUser.getUserId());
        for (TradeAndCardInfoVO tradeInfo : list) {
            System.out.println(tradeInfo);
        }
    }

    /**
     * 取款
     *
     * @author: 元初
     */
    private static void withdrawal() {
        while (true) {
            System.out.println("请选择要取款的银行卡");
            List<BankCard> list = bankCardController.findCardsByUserId(loginUser.getUserId());
            if (list.size() <= 0) {
                System.out.println("暂未开卡，请进行开卡");
                return;
            }
            for (int i = 0; i < list.size(); i++) {
                System.out.println((i + 1) + ":" + list.get(i));
            }
            int choice = sc.nextInt();
            if (choice > list.size()) {
                System.out.println("选择有误，请重新选择");
            } else {
                //输入正确
                System.out.println("请输入要取款的金额");
                double withdrawal = sc.nextDouble();
                BankCard card = list.get(choice - 1);
                if (withdrawal > card.getCardBalance()) {
                    System.out.println("余额不足，请先进行存款");
                    return;
                } else {
                    boolean isSuccess = bankCardController.withdrawal(withdrawal, card);
                    if (isSuccess) {
                        System.out.println("取款成功");
                        return;
                    } else {
                        System.out.println("未知错误");
                        return;
                    }
                }
            }
        }
    }
}
